#- coding: utf8 -*-
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
#from pms.task_management.models import Task, Status
from pms.task_management.models import *
from datetime import datetime, timedelta
from django.contrib.auth.models import User as ModelUser
from django.contrib.auth.decorators import login_required

STATUS_MAPPING = {
}
STATUS_LIST = []
USER_LIST = []

def init(): 
    for status in Status.objects.all():
        STATUS_MAPPING[status.id] = status.name
        STATUS_LIST.append(status)

    for user in ModelUser.objects.all():
        USER_LIST.append(user)
        print user.first_name

    print "------ Init Metadata BEGIN ------"
    print "status: ", STATUS_MAPPING
    print "user: ", USER_LIST
    print "------ Init Metadata END ------"

init()

def add_or_update(request, project_id):
    task = None
    hi = HistoryItem()
    hi.user_id = request.session['_auth_user_id']
    user = User.objects.get(id = hi.user_id)
    hi.user_name = user.first_name
    hi.date_created = datetime.now()

    if len(request.GET['id']) > 0:
        print u"编辑一个已经有的task"
        id = int(request.GET['id'])
        task = Task.objects.get(id=id)
        task.updated_date = datetime.now()

        hi.action_name = '编辑'
        hi.action_id = 2
    else:
        print u"添加一个新的task"
        task = Task();
        task.created_date = datetime.now()
        task.is_deleted = False

        hi.action_name = '添加'
        hi.action_id = 1

    task.name = request.GET['name']
    hi.object_name = task.name
    hi.object_id = 1
    hi.object_type_id = 1
    hi.object_type_name = "任务"

    if len(request.GET['due_date']) > 0:
        task.due_date = request.GET['due_date']
    else:
        task.due_date = None

    if len(request.GET['start_date']) > 0:
        task.start_date = request.GET['start_date']
    else:
        task.start_date = None
        
    task.assignee = User(id = request.GET['assignee'])
    task.note = request.GET['note']
    task.tag = request.GET['tag']
    task.status = Status(id = int(request.GET['status']))
    task.project = Project(id = project_id)

    if len(request.GET['estimated_mds']) > 0:
        task.estimated_mds = float(request.GET['estimated_mds'])
    else:
        task.estimated_mds = None


    task.save()
    hi.save()

    return HttpResponse("OK")

def clean_str(str1, size=1000):
    if str1 == None:
        return ""
    elif size != 1000 and len(unicode(str1)) > size:
        return str1[0:size]
    else:
        return str1

@login_required
def complete(request, project_id):
    id = int(request.GET['id'])
    print "complete the task:", id
    task = Task.objects.get(id=id)
    if task == None:
        return HttpResponse("ERROR")
    else:
        task.is_finished = True
        task.updated_date = datetime.now()
        task.save()

        return  HttpResponse("OK")

@login_required
def delete(request, project):
    id = int(request.GET['id'])
    task = Task.objects.get(id=id)
    if task == None:
        return HttpResponse("ERROR")
    else:
        task.is_deleted = True
        task.status = Status(id = -1)
        task.save()

        return HttpResponse("OK")

@login_required
def not_completed(request, project_id):
    tasks = Task.objects.filter(is_deleted = False)\
                        .filter(is_finished = False)\
                        .order_by('due_date')

    return inner_help(request, project_id, tasks)

@login_required
def all(request, project_id):
    tasks = Task.objects.all()
    return inner_help(request, project_id, tasks)

@login_required
def completed(request, project_id):
    tasks = Task.objects.filter(is_finished = True)
    return inner_help(request, project_id, tasks)

@login_required
def weekly_report(request, project_id):
    today = datetime.today()
    weekday = today.weekday()
    start_day = today - timedelta(days = weekday, hours = today.hour, minutes = today.minute, seconds = today.second)

    print "start day: ", start_day
    print "today: ", today
    tasks = Task.objects.filter(is_finished = True)\
                        .filter(start_date__gte = start_day)

    return inner_help(request, project_id, tasks)

@login_required
def deleted(request, project_id):
    tasks = Task.objects.filter(is_deleted=1)
    return inner_help(request, project_id, tasks)

@login_required
def due_today(request, project_id):
    tasks = Task.objects.filter(due_date=datetime.today())
    return inner_help(request, project_id, tasks)

@login_required
def updated_today(request, project_id):
    tasks = Task.objects.filter(updated_date=datetime.today())
    return inner_help(request, project_id, tasks)

@login_required
def completed_today(request, project_id):
    tasks = Task.objects.filter(updated_date=datetime.today())\
                        .filter(is_finished = True)

    return inner_help(request, project_id, tasks)

@login_required
def search(request, project_id):
    tasks = None
    if request.GET.has_key('tag'):
        tag = request.GET['tag'].strip()
        tasks = Task.objects.filter(tag__contains=tag)

    if request.GET.has_key('assignee'):
        assignee = request.GET['assignee'].strip()
        tasks = Task.objects.filter(assignee__id=assignee)

    if request.GET.has_key('due_date'):
        due_date = request.GET['due_date'].strip()
        tasks = Task.objects.filter(due_date=due_date)

    if request.GET.has_key('start_date'):
        start_date = request.GET['start_date'].strip()
        tasks = Task.objects.filter(start_date=start_date)

    if request.GET.has_key('status'):
        status_id = request.GET['status'].strip()
        tasks = Task.objects.filter(status__id=int(status_id))


    return inner_help(request, project_id, tasks)

@login_required
def inner_help(request, project_id, tasks):
    if tasks != None:
        tasks = tasks.filter(is_deleted = False)\
                 .filter(project__id = project_id)
    else:
        tasks = Task.objects.filter(is_deleted = False)\
                 .filter(project__id = project_id)

    server_host = request.get_host()
    project = Project.objects.get(id = project_id)

    t = None
    if not(request.GET.has_key('ajax')):
        t = get_template('frame.html')
    else:
        t = get_template('ajax.html')

    total_estimated_mds = 0
    for task in tasks:
        print "start: ", task.start_date, ", end: ", task.end_date
        if task.estimated_mds != None:
            total_estimated_mds += task.estimated_mds

    html = t.render(Context({ "tasks": tasks,
            "server_host": server_host,
            "total_estimated_mds": total_estimated_mds,
            "project": project,
            "STATUS_MAPPING": STATUS_MAPPING,
            "USER_LIST": USER_LIST,
            "STATUS_LIST": STATUS_LIST}))

    return HttpResponse(html)

@login_required
def projects(request):
    user = User.objects.get(id = request.session['_auth_user_id'])
    project_set = user.project_set.all()
    for project in project_set:
        print project.name

    t = get_template('projects.html')
    return HttpResponse(t.render(Context({'projects': project_set})))

